package com.adong.tv.ui;

import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.adong.tv.R;
import com.adong.tv.data.ApiConfig;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;

/**
 * 播放器Activity
 */
public class PlayerActivity extends FragmentActivity {
    
    public static final String EXTRA_URL = "url";
    public static final String EXTRA_TITLE = "title";
    public static final String EXTRA_EPISODE = "episode";
    public static final int RESULT_PLAY_NEXT = 1002;  // 添加结果码
    
    private PlayerView playerView;
    private ExoPlayer player;
    private ProgressBar progressBar;
    private TextView errorTextView;
    private TextView titleTextView;
    
    private String videoUrl;
    private String title;
    private String episode;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        
        // 获取参数
        videoUrl = getIntent().getStringExtra(EXTRA_URL);
        title = getIntent().getStringExtra(EXTRA_TITLE);
        episode = getIntent().getStringExtra(EXTRA_EPISODE);
        
        // 如果是外部链接，需要拼接播放前缀
        if (!videoUrl.startsWith("http")) {
            videoUrl = ApiConfig.getCurrentApi().getPlayUrl() + videoUrl;
        }
        
        // 初始化视图
        initViews();
        
        // 初始化播放器
        initPlayer();
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        playerView = findViewById(R.id.player_view);
        progressBar = findViewById(R.id.progress_bar);
        errorTextView = findViewById(R.id.tv_error);
        titleTextView = findViewById(R.id.tv_title);
        
        // 设置标题
        if (title != null && episode != null) {
            titleTextView.setText(title + " - " + episode);
        } else if (title != null) {
            titleTextView.setText(title);
        }
    }
    
    /**
     * 初始化播放器
     */
    private void initPlayer() {
        // 创建播放器
        player = new ExoPlayer.Builder(this).build();
        playerView.setPlayer(player);
        
        // 设置媒体
        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
        player.setMediaItem(mediaItem);
        
        // 准备播放
        player.prepare();
        player.play();
        
        // 设置监听器
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_ENDED) {
                    // 播放完成，返回结果并关闭播放器
                    setResult(RESULT_PLAY_NEXT);
                    finish();
                } else if (state == Player.STATE_READY) {
                    progressBar.setVisibility(View.GONE);
                } else if (state == Player.STATE_BUFFERING) {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
            
            @Override
            public void onPlayerError(com.google.android.exoplayer2.PlaybackException error) {
                progressBar.setVisibility(View.GONE);
                errorTextView.setVisibility(View.VISIBLE);
                errorTextView.setText("播放失败: " + error.getMessage());
            }
        });
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 处理返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 返回时不触发自动播放下一集
            setResult(RESULT_CANCELED);
            finish();
            return true;
        }
        
        // 处理其他按键
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.pause();
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.play();
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
            player = null;
        }
    }
} 